//
//  LHHomeTableViewController.swift
//  sinaWeibo
//
//  Created by LiHong on 15/10/26.
//  Copyright © 2015年 LiHong. All rights reserved.
//

import UIKit
import SVProgressHUD
import SDWebImage

enum LHStatusCellReuseIdentifier: String{
    case NormalCell = "NormalCell"
    case RetweetCell = "RetweetCell"
}

class LHHomeTableViewController: LHBaseTableViewController {

    //MARK; - 属性
    
   // let reuseId: String = "cell"
    
    private var statuses: [LHStatus]? {
        didSet{
            tableView.reloadData()
        }
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        if !LHUserAccount.userLogin() {
            return
        }
        setupNavigationBar()
        prepareTableView()
        
        // 设置刷新
//        refreshControl = LHRefreshControl()
//        
//        refreshControl?.addTarget(self, action: "loadData", forControlEvents: UIControlEvents.ValueChanged)
//        
//        refreshControl?.beginRefreshing()
//        
//        refreshControl?.sendActionsForControlEvents(UIControlEvents.ValueChanged)
        
    //    loadData()
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "selectedPicture:", name: LHPictureViewCellSelectedPictureNotification, object: nil)
        
    }
    
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    func selectedPicture(notification: NSNotification) {
        
        guard let urls = notification.userInfo?[LHPictureViewCellSelectedPictureURLKey] as? [NSURL] else {
            print("urls有问题")
            return
        }
        
        guard let index = notification.userInfo?[LHPictureViewCellSelectedPictureIndexKey] as? Int else {
            print("index有问题")
            return
        }
//
        let photoBrowserVc = LHPhotoBrowerViewController(urls: urls, selectedIndex: index)
        presentViewController(photoBrowserVc, animated: true, completion: nil)
        
    }
    
    func loadData() {
        print("加载微博数据")
        var since_id = statuses?.first?.id ?? 0
        var max_id = 0

        if pullUpView.isAnimating() {
            since_id = 0
            max_id = statuses?.last?.id ?? 0 //设置为最后一条微博的ID
        }
//        LHStatus.loadStatus(since_id, max_id: max_id) { (statuses, error) -> () in
//            
//        }
        LHStatus.loadStatus(since_id, max_id: max_id) { (statuses, error) -> () in
            self.refreshControl?.endRefreshing()
            
            self.pullUpView.stopAnimating()
        
            if error != nil {
                SVProgressHUD.showErrorWithStatus("网络不给力，加载数据失败", maskType: SVProgressHUDMaskType.Black)
                return
            }
            // 返回最新微博
            if since_id > 0 {
                let count = statuses?.count ?? 0
                self.showTipView(count)
            }
            
            // 没有错误，是否有数据
            if statuses == nil || statuses?.count == 0 {
                SVProgressHUD.showInfoWithStatus("没有新的微博数据", maskType: SVProgressHUDMaskType.Black)
                return
            }
            
            if since_id > 0 {// 下拉刷新
                print("下拉刷新,获取到: \(statuses?.count)")
                self.statuses = statuses! + self.statuses!
            }else if max_id > 0 {// 上拉加载更多数据
                print("上拉加载更多数据,获取到: \(statuses?.count)")
                self.statuses = self.statuses! + statuses!
            }else {
                
                self.statuses = statuses
                //  print("statuses = \(statuses)")
                print("加载了 \(statuses!.count) 条信息")
            }
        }
    }
    
    private func showTipView(count: Int) {
        let tipLabelHeight: CGFloat = 44
        let tipLabel = UILabel()
        tipLabel.frame = CGRect(x: 0, y: -20 - tipLabelHeight, width: UIScreen.mainScreen().bounds.width, height: tipLabelHeight)
        
        tipLabel.textColor = UIColor.whiteColor()
        tipLabel.backgroundColor = UIColor.orangeColor()
        tipLabel.font = UIFont.systemFontOfSize(16)
        tipLabel.textAlignment = NSTextAlignment.Center
        
        tipLabel.text = count == 0 ? "没有新微博" : "加载了 \(count) 条微博"
        
        navigationController?.navigationBar.insertSubview(tipLabel, atIndex: 0)
        
        let duration = 0.75
        
        UIView.animateWithDuration(duration, animations: { () -> Void in
            
            tipLabel.frame.origin.y = tipLabelHeight
            
            }) { (_) -> Void in
                UIView.animateWithDuration(duration, delay: 0.3, options: UIViewAnimationOptions(rawValue: 0), animations: { () -> Void in
                    
                    tipLabel.frame.origin.y = -20 - tipLabelHeight
                    
                    }, completion: { (_) -> Void in
                        tipLabel.removeFromSuperview()
                })
        }
        
        
        
    }
    
    //MARK: -准备tableView
    private func prepareTableView() {
        tableView.tableFooterView = pullUpView
        //MARK: - 注册
        tableView.registerClass(LHNormalCell.self, forCellReuseIdentifier: LHStatusCellReuseIdentifier.NormalCell.rawValue)
        
        tableView.registerClass(LHRetweetCell.self, forCellReuseIdentifier: LHStatusCellReuseIdentifier.RetweetCell.rawValue)
        
        tableView.separatorStyle = UITableViewCellSeparatorStyle.None
//        tableView.estimatedRowHeight = 300
//        tableView.rowHeight = UITableViewAutomaticDimension
        refreshControl = LHRefreshControl()
        
        refreshControl?.addTarget(self, action: "loadData", forControlEvents: UIControlEvents.ValueChanged)
        
        refreshControl?.beginRefreshing()
        
        refreshControl?.sendActionsForControlEvents(UIControlEvents.ValueChanged)
    }
    
    private func setupNavigationBar(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "navigationbar_friendsearch")
        navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop")
        // title按钮
        
        // 获取用户名
        let title = LHUserAccount.loadAccount()?.name ?? "没有名称"
        let button = LHHomeTitleButton(title: title)
        button.addTarget(self, action: "homeTitleClick:", forControlEvents: UIControlEvents.TouchUpInside)
        navigationItem.titleView = button
    }
    
    @objc private func homeTitleClick(button: UIButton) {
        button.selected = !button.selected
        var transform: CGAffineTransform = CGAffineTransformIdentity
        if button.selected {
            transform = CGAffineTransformMakeRotation(CGFloat(M_PI - 0.01))
        }else{
            transform = CGAffineTransformIdentity
        }
        UIView.animateWithDuration(0.25) { () -> Void in
            
            button.imageView?.transform = transform
        }
    }
    
    
    

    // MARK: - 数据源方法

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return statuses?.count ?? 0
    }

    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let status = statuses![indexPath.row]
        let cell = tableView.dequeueReusableCellWithIdentifier(status.cellId()) as! LHStatusesCell

        // Configure the cell...
        cell.statuses = status
        
        if indexPath.row == statuses!.count - 1 && !pullUpView.isAnimating() {
            pullUpView.startAnimating()
            
            loadData()
        }
        
        return cell
    }
    
    // 行高
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        let status = statuses![indexPath.row]
        
        if let rowHeight = status.rowHeight {
            return rowHeight
        }
        let id = status.cellId()
        
        let cell = tableView.dequeueReusableCellWithIdentifier(id) as! LHStatusesCell
        
        let rowHeight = cell.rowHeight(status)
        
        status.rowHeight = rowHeight
        
        return rowHeight
        
    }

    //MARK: - 懒加载
    private lazy var pullUpView: UIActivityIndicatorView = {
        let indicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
        
        indicator.color = UIColor.magentaColor()
        return indicator
    }()
    /*
    // Override to support conditional editing of the table view.
    override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return false if you do not want the specified item to be editable.
        return true
    }
    */

    /*
    // Override to support editing the table view.
    override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        if editingStyle == .Delete {
            // Delete the row from the data source
            tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
        } else if editingStyle == .Insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }    
    }
    */

    /*
    // Override to support rearranging the table view.
    override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {

    }
    */

    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return false if you do not want the item to be re-orderable.
        return true
    }
    */

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
